package com.tronapi.c.facade;

import com.alibaba.fastjson.JSON;
import com.tronapi.c.facade.model.TronHttpApiRequest;
import com.tronapi.c.utils.HttpClientUtil;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 对接 tron http 接口
 */
@Component
public class TronHttpApiServiceFacadeImpl implements TronHttpApiServiceFacade {

    private static String nodeAddress = "http://112.121.167.2:8090/wallet/";

    // 47.241.20.47 & 161.117.85.97 &161.117.224.116 &161.117.83.38
    private static String OFFICIAL_NODE_ADDRESS = "http://47.241.20.47/wallet/";
    /**
     * 波场api缓存
     */
    private static Map<String, String> API_CACHE = new HashMap<>();

    static {
        API_CACHE.put("createaccount", nodeAddress + "createaccount");
        API_CACHE.put("getaccount", nodeAddress + "getaccount");
        API_CACHE.put("getblockbynum", nodeAddress + "getblockbynum");
        API_CACHE.put("getnowblock", nodeAddress + "getnowblock");
        API_CACHE.put("gettransactioninfobyid", nodeAddress + "gettransactioninfobyid");
        API_CACHE.put("gettransactioninfobyblocknum", nodeAddress + "gettransactioninfobyblocknum");
        API_CACHE.put("listnodes", nodeAddress + "listnodes");
        API_CACHE.put("getblockbalance", OFFICIAL_NODE_ADDRESS + "getblockbalance");
    }

    @Override
    public Object invoke(TronHttpApiRequest request) {
        String url = API_CACHE.get(request.getApiKey());
        if (request.getRequestType().equalsIgnoreCase("post")) {
            return JSON.parseObject(HttpClientUtil.syncPost(url, request.getParams()));
        }
        return JSON.parseObject(HttpClientUtil.syncGet(url, request.getParams()));
    }
}
